<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="100px">
      <el-form-item label="消费产品:" prop="consumerProducts">
        {{ formData.consumerProducts }}
      </el-form-item>
      <el-form-item label="使用项目:" prop="project">
        {{ projectName }}
      </el-form-item>
      <el-form-item label="消费账户:" prop="consumerAccount">
        <el-radio-group v-model="formData.consumerAccount">
          <el-radio :label="username">{{ username }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="可用额度:" prop="balance">
        <span>999次</span>
        <el-button link type="primary" class="ml-10px" @click="handleBuyConsult"> 购买咨询 > </el-button>
      </el-form-item>
      <el-form-item label="使用额度:" prop="consumerLimit">
        <el-input v-model.number="formData.consumerLimit" placeholder="请输入使用额度" type="number" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import * as TestCommitApi from '@/api/commit'
import { useUserStore } from '@/store/modules/user'
import { useAppStore } from '@/store/modules/app'
import { getMyProject } from '@/api/view'

defineOptions({ name: 'ConsultForm' })
const userStore = useUserStore()
const appStore = useAppStore()
const username = userStore.getUser.nickname
const id = userStore.getUser.id
const projectId = computed(() => appStore.getSelectProject)
const allProject = ref([] as any)
const projectName = computed(() => {
  return allProject.value.find(i => i.id == projectId.value).name
})
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中:1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({} as any)
const getAllProject = async () => {
  let res = await getMyProject()
  allProject.value = res
}
const validateNonNegativeInteger = (rule, value, callback) => {
  const num = parseFloat(value);
  if (isNaN(num) || num < 1 || !Number.isInteger(num)) {
    formData.value.consumerLimit = 1; // 验证失败时将值重置为1
    callback(new Error('请输入正整数，已重置为1'));
  } else {
    callback(); // 验证通过
  }
}
const formRules = reactive({
  consumerLimit: [
    { required: false, message: '此项必填', trigger: 'blur' },
    {
      validator: validateNonNegativeInteger, // 使用新方法作为验证器
      trigger: ['blur', 'change'],
    }
  ]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (name) => {
  dialogVisible.value = true
  dialogTitle.value = '确认消费'
  resetForm(name)
}

getAllProject()

/** 重置表单 */
const resetForm = (name) => {
  formData.value = {
    consumerProducts: name,
    consumerAccount: username,
    relatedConsumerNumber: '',
    consumerLimit: 1,
    testingUserId: id,
    projectId: projectId.value,
    notes: ''
  }
  formRef.value?.resetFields()
}
defineExpose({ open })

/** 提交表单 */
const emit = defineEmits(['success'])
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    await TestCommitApi.createTestRecord(data)
    message.success('提交成功')
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
const handleBuyConsult = ()=>{
  message.warning('此功能暂未上线！')
}
</script>
